from PySide6.QtWidgets import (QApplication, QMainWindow, QWidget, QVBoxLayout, 
                             QHBoxLayout, QButtonGroup)
import sys
from view.StudentButton import StudentButton
from view.CourseBox import CourseBox
from view.StudentList import StudentList
from view.SeatGrid import SeatGrid
from view.AbsenceBox import AbsenceBox
from view.DateBox import DateBox
from view.StudentInfo import StudentInfo
from view.BehaviorBox import BehaviorBox
from view.MenuBar import MenuBar
from util.VoiceUtil import VoiceUtil

# 软件信息配置
APP_NAME = {
    "en": "ClassroomPin",  # 英文标识（代码内部使用）
    "zh": "教室图钉 课堂点名系统"    # 中文显示名称
}
__version__ = "0.8.0"  # 语义化版本


class ClassroomPinApp(QMainWindow):
    def __init__(self):
        super().__init__()
        
        # 语音播报工具单实例
        self.voice_util = VoiceUtil()
        
        # 学生按钮组，用来保存所有学生
        self.stu_group = QButtonGroup(self)
        self.stu_group.setExclusive(True)  # 确保单选互斥
        # self.stu_group.buttonClicked.connect(self.on_student_clicked)
        self.stu_list = StudentList() # 左侧学生列表
        self.seat_grid = SeatGrid(on_seat_click=self.on_seat_click) # 座位网络
        self.lev_box = AbsenceBox("请假", on_leave_click=self.on_lev_click) # 请假栏
        self.abs_box = AbsenceBox("缺勤", on_leave_click=self.on_abs_click) # 缺勤栏
        self.date_box = DateBox() # 日期栏
        self.stu_info = StudentInfo() # 学生基本信息
        self.behavior_box = BehaviorBox(self) # 行为记录
        # 初始化UI框架
        self.init_ui()
        self.setMenuBar(MenuBar(self))
        # 显示窗口
        self.show()
        # print("UI初始化完成")

    def init_ui(self):
        """初始化UI"""
        self.setWindowTitle("课堂点名系统")
        self.setGeometry(100, 100, 1200, 720)

        # 主窗口布局
        main_layout = QHBoxLayout()
        main_widget = QWidget()
        main_widget.setLayout(main_layout)
        self.setCentralWidget(main_widget)
        
        # 左侧面板 - 学生列表
        left_panel = QVBoxLayout()
        left_panel_widget = QWidget()
        left_panel_widget.setLayout(left_panel)
        self._course_box = CourseBox()
        self._course_box.students_loaded.connect(self.handle_students_loaded)
        self._course_box.btn_save.clicked.connect(self.handle_save_records)
        self._course_box.random_requested.connect(self.random_select)
        left_panel.addWidget(self._course_box._container)
        left_panel.addWidget(self.stu_list._container)

        # 中间面板 - 座位网格
        center_panel = QVBoxLayout()
        center_panel_widget = QWidget()
        center_panel_widget.setLayout(center_panel)
        center_panel.addWidget(self.seat_grid._container)
        center_panel.addWidget(self.lev_box._container)
        center_panel.addWidget(self.abs_box._container)

        # 右侧面板 - 学生详情
        right_panel = QVBoxLayout()
        right_panel_widget = QWidget()
        right_panel_widget.setLayout(right_panel)
        self.date_box.date_changed.connect(self.handle_date_change)
        right_panel.addWidget(self.date_box._container)
        right_panel.addWidget(self.stu_info._container)
        right_panel.addWidget(self.behavior_box._container)

        # 添加所有面板到主布局
        main_layout.addWidget(left_panel_widget, stretch=1)
        main_layout.addWidget(center_panel_widget, stretch=3)
        main_layout.addWidget(right_panel_widget, stretch=2)
        
    def on_seat_click(self, row, col, text):
        # 若有已选中的学生按钮，则将该学生按钮移动到对应的座位上。
        btn = self.stu_group.checkedButton()
        if btn and btn.student.update_seat(text, self.date_box.get_date()):
            self.seat_grid.addWidget(btn, row, col)
            self.stu_info.update_info(btn.student, self.date_box.get_date())
    
    def on_lev_click(self, event):
        # print("请假区被点击")  # 实际处理逻辑
        btn = self.stu_group.checkedButton()
        if btn and btn.student.update_seat("请假", self.date_box.get_date()):
            self.lev_box.addWidget(btn)
            self.stu_info.update_info(btn.student, self.date_box.get_date())

    def on_abs_click(self, event):
        # print("缺勤区被点击")  # 实际处理逻辑
        btn = self.stu_group.checkedButton()
        if btn and btn.student.update_seat("缺勤", self.date_box.get_date()):
            self.abs_box.addWidget(btn)
            self.stu_info.update_info(btn.student, self.date_box.get_date())

    def on_stu_toggled(self, stu_btn:StudentButton):
        if(stu_btn.isChecked()):
            self._update_display(stu_btn)

    def handle_students_loaded(self, _students, _behaviors):
        for button in self.stu_group.buttons()[:]:  # 创建副本避免迭代时修改
            if button in self.stu_group.buttons():
                self.stu_group.removeButton(button)  # 从按钮组移除
                button.deleteLater()  # 标记为待删除（Qt自动回收）
                button.setParent(None)  # 解除父子关系
        self.stu_info.clear_info()
        self.behavior_box.clear_all()
        
        for _student in _students:  # 添加新学生
            _stu_btn = StudentButton(_student)
            _stu_btn.toggled.connect(lambda checked, btn=_stu_btn: self.on_stu_toggled(btn))
            self.stu_group.addButton(_stu_btn)
        
        for _behavior in _behaviors:  # 添加行为按钮
            self.behavior_box.add_button(_behavior["name"])
        
        self.stu_list.reload_buttons(self.stu_group)  # 刷新UI

    def handle_date_change(self):
        """处理日期变更事件"""
        selected_button = self.stu_group.checkedButton()
        if selected_button:
            self._update_display(selected_button)

    def handle_save_records(self):
        students = [btn.student for btn in self.stu_group.buttons()]
        self._course_box.save_records(students)

    def _update_display(self, button: StudentButton):
        """更新界面显示内容"""
        date_str = self.date_box.get_date()
        current_btn = self.stu_group.checkedButton()

        # 更新学生信息显示
        self.stu_info.update_info(current_btn.student, date_str)
        # 更新行为按钮显示
        self.behavior_box.update_buttons_from_data(current_btn.student, date_str)
        # 语音播报姓名
        self.voice_util.speak(current_btn.student.name)

    def sync_to_current_student(self):
        """同步当前学生的行为数据"""
        current_btn = self.stu_group.checkedButton()
        current_stu = current_btn.student
        current_date = self.date_box.get_date()
        # 获取行为数据并同步到学生对象
        new_behavior = self.behavior_box.get_behavior_data(filter_zero=False)
        if current_date not in current_stu.date_records:
            current_stu.date_records[current_date] = {"behavior": {}}
        
        current_stu.date_records[current_date]["behavior"] = new_behavior
        return True

    def random_select(self):
        """随机选择学生"""
        buttons = self.stu_group.buttons()
        if not buttons:
            return
            
        import random
        selected = random.choice(buttons)
        selected.setChecked(True)
        # self._update_display(selected)


if __name__ == "__main__":
    app = QApplication(sys.argv)
    window = ClassroomPinApp()
    window.show()
    sys.exit(app.exec())